package itbour.onetouchshow.activity.video.videobg;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andview.adapter.BaseRecyclerHolder;
import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lsjr.callback.EncryBeanCallBack;
import com.lsjr.utils.HttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.base.BaseDialogMvpActivity;
import itbour.onetouchshow.base.BaseRefreshAdapter;
import itbour.onetouchshow.base.IntentCode;
import itbour.onetouchshow.bean.LoadVideoUserDocBg;
import itbour.onetouchshow.bean.page.Page;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.constants.platform.WorkPlatform;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.recycleviewmanager.FastScrollManger;


public class VideobgActivity extends BaseDialogMvpActivity<VideobgContract.View, VideobgPresenter> implements VideobgContract.View {
    public static final int ON_REFRESH = 1;
    private static final int ON_LOAD = 2;
    @BindView(R.id.id_back_top)
    public ImageView mImageViewRebackTop;
    protected String mDocId;
    protected String subType;
    @BindView(R.id.ry_title)
    RelativeLayout ryTitle;
    private List<LoadVideoUserDocBg.ListBean> mdata = new ArrayList<>();
    private Page page;
    private int pullStatus;
    private int mPageIndex = 0;
    private XRefreshView xRefreshView;
    private VideoBgViewpagerAdapter adapter;

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_popup_bg_select;
    }

    @Override
    protected void onResume() {
        super.onResume();
        // overridePendingTransition(0, 0);  //解决退出动画无效
    }

    @Override
    protected void onPause() {
        super.onPause();
        //overridePendingTransition(0, 0);  //解决退出动画无效
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        getToolBarView().getLeftimageView().setVisibility(View.VISIBLE);
        getToolBarView().getLeftimageView().setImageResource(R.mipmap.return_icon);
        getToolBarView().getLeftimageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        setTitleText("选择边框");
        //getToolBarView().setVisibility(View.GONE);

    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        super.afterCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            mDocId = extras.getString(AppConst.DOCID);
            subType = extras.getString(WorkPlatform.TYPE);
        }
        iniView();
        onLoadData();
    }

    protected void iniView() {
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        xRefreshView = findViewById(R.id.id_xfresh);
        xRefreshView.setAutoRefresh(false);
        xRefreshView.setAutoLoadMore(true);
        xRefreshView.setPinnedTime(1000);
        xRefreshView.stopLoadMore(false);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        recyclerView.setHasFixedSize(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                pullStatus = ON_REFRESH;
                page.loadPage(true);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                pullStatus = ON_LOAD;
                page.loadPage(false);
            }
        });


        ImageView closeImage = findViewById(R.id.id_ig_close);
        closeImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();

            }
        });

        adapter = new VideoBgViewpagerAdapter(getApplicationContext(), mdata, R.layout.item_bg_seletor);
        FastScrollManger recyclerViewLayoutManager = new FastScrollManger(3, StaggeredGridLayoutManager.VERTICAL);
        //recyclerViewLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.setLayoutManager(recyclerViewLayoutManager);
        //GridLayoutManager  recyclerViewLayoutManager= new GridLayoutManager(getApplicationContext(), 3);
        // recyclerView.setLayoutManager(recyclerViewLayoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(getApplicationContext()));
        mImageViewRebackTop.setVisibility(View.INVISIBLE);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int lastBottomCompletelyEmergedItemPosition =
                            recyclerViewLayoutManager.findLastBottomCompletelyEmergedItemPosition();
                    if (lastBottomCompletelyEmergedItemPosition > 0) {
                        if (mImageViewRebackTop != null) {
                            mImageViewRebackTop.setVisibility(View.VISIBLE);
                        }
                    } else {
                        if (mImageViewRebackTop != null) {
                            mImageViewRebackTop.setVisibility(View.INVISIBLE);
                        }
                    }
                }
            }
        });

        mImageViewRebackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerViewLayoutManager.scrollToPositionWithOffset(0, 0);
                mImageViewRebackTop.setVisibility(View.INVISIBLE);
            }
        });
    }

    public void onLoadData() {
        page = new Page() {
            @Override
            public void load(int param1, int param2) {
                mPageIndex = param1;
                loadVideoUserDocBg();
            }
        };
        pullStatus = ON_REFRESH;
        page.loadPage(true);
    }


    public void loadVideoUserDocBg() {

        L_.e("loadVideoUserDocBg mDocId" + mDocId);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", mDocId);
        //pageNum	是
        stringObjectHashMap.put("pageNum", mPageIndex);
        stringObjectHashMap.put("pageSize", AppConst.PAGE_SIZE);
        HttpUtils.getInstance().executeGet(AppConfig.GETVIDEOUSERDOCBGLIST_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                page.finishLoad(false);
                //T_.showToastReal(exception);
                L_.e("bg onSuccess" + exception);
                //endNetRequse(null);
            }

            @Override
            protected void onSuccess(String response) {
                L_.e("bg onSuccess" + response);
                page.finishLoad(true);
                LoadVideoUserDocBg loadVideoUserDocBg = new Gson().fromJson(response, LoadVideoUserDocBg.class);
                List<LoadVideoUserDocBg.ListBean> list = loadVideoUserDocBg.getList();
                if (list != null && list.size() > 0) {
                    endNetRequse(list);
                } else {
                    xRefreshView.setLoadComplete(true);
                }

            }
        });
    }

    public void endNetRequse(List<LoadVideoUserDocBg.ListBean> data) {
        if (pullStatus == ON_LOAD) {
            mdata.addAll(data);
            xRefreshView.stopLoadMore();
        } else if (pullStatus == ON_REFRESH) {
            mdata = data;
            xRefreshView.stopRefresh();
            xRefreshView.setLoadComplete(false);
        }
        adapter.notifyDataSetChanged(mdata);
        pullStatus = 0;
    }

    protected void onChangeBg(LoadVideoUserDocBg.ListBean listBean) {
        int bgId = listBean.getId();
        L_.e(listBean.getId() + "作品ID");
        Bundle bundle = new Bundle();
        bundle.putInt(IntentCode.INCHING_TYPE, IntentCode.SUB_TYPE_PRODUCE);
        bundle.putInt(IntentCode.TAG, IntentCode.INTENT_VERTICAL_VIDEP);
        bundle.putInt(AppConst.BGID, Integer.valueOf(bgId));
        bundle.putString(AppConst.DOCID, mDocId);
        bundle.putString(WorkPlatform.TYPE, WorkPlatform.MOUDLE);
        Intent intent = new Intent();
        intent.putExtras(bundle);
        setResult(20000, intent);
        // openActivity(CommoninchingVideoBgActivity.class, bundle);
        finish();
    }

    public class VideoBgViewpagerAdapter extends BaseRefreshAdapter<LoadVideoUserDocBg.ListBean> {

        public VideoBgViewpagerAdapter(Context context, List<LoadVideoUserDocBg.ListBean> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder var1, LoadVideoUserDocBg.ListBean listBean, int var3) {
            ImageView imageView = var1.getView(R.id.id_ig);
            TextView tvName = var1.getView(R.id.id_tv_name);
            TextView tvCount = var1.getView(R.id.id_tv_count);
            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
            int width = UIUtils.WHD()[0] / 3 - UIUtils.dp2px(15);
            int height = width * listBean.getH() / listBean.getW();
            String imUrl = ImageLoader.getShrinkImageUrl(listBean.getThumb(), width, height);
            layoutParams.width = width;
            layoutParams.height = height;
            // ImageLoader.getInstance().showImage(context,imUrl, imageView);
            Glide.with(getApplicationContext()).applyDefaultRequestOptions(new RequestOptions()
                    .apply(new RequestOptions()).placeholder(R.drawable.place_icon).
                            error(R.drawable.place_icon)).load(imUrl).into(imageView);

            tvName.setText(listBean.getName() + "");
            tvCount.setText(listBean.getUseCount() + "人使用");
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onChangeBg(listBean);
                }
            });
        }
    }


}
